<template>
    <div id="add-edit-model">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="140px" :rules="rules">
                <el-row>
                    <el-divider content-position="left">基础信息</el-divider>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="所属年份" prop="n_Year">
                            <el-date-picker
                                clearable
                                v-model="ruleForm.n_Year"
                                type="year"
                                value-format="YYYY"
                                placeholder="选择年份"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="描述" prop="v_Describe">
                            <el-input
                                v-model="ruleForm.v_Describe"
                                autosize
                                type="textarea"
                                placeholder="请输入描述"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="应急演练文件类型" prop="n_Type">
                            <el-select 
                                filterable
                                class="m-2" 
                                placeholder="请选择应急演练文件类型" 
                                v-model="ruleForm.n_Type"
                            >
                                <el-option
                                    v-for="item in typeOption"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-divider content-position="left">文件上传</el-divider>
                    <div style="padding: 0 20px;width: 100%;">
                        <FileView
                            ref="fileRef"
                            isAccept=""
                            :isNeedRequest="true"
                            :fileInfo="fileInfo"
                            :componentKey="isAlter"
                        />
                    </div>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取 消</el-button>
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">提 交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue'
import { FormInstance, FormRules, ElButton, ElCol, ElDatePicker, ElDialog, ElForm, ElFormItem, ElInput, ElOption, ElRow, ElSelect } from 'element-plus'
import { SMSDRFileAdd , SMSDRFileUpdate , sysDictDataList } from '/@/api/centerControl/sms';
import FileView from '../file-view.vue';
import { sysFileInfoYitId , sysFileInfoMultipleUpload } from '/@/api/centerControl/pubilc';

/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    id?: Number,
    n_Year: String, // 所属年份
    v_Describe: String, // 描述
    n_Type: Number, // 应急演练文件类型
    l_FileId: any, // 应急文件id
}
export default defineComponent( {
    name: 'add-edit-DrillPlan',
    components: {FileView},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const fileInfo = ref('');
        let sourceId: any;
        const fileRef:any = ref(null);

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 所属年份
            n_Year: [
				{ required: true, message: '所属年份', trigger: 'change' },
			],
            // 描述
            v_Describe: [
				{ required: true, message: '描述', trigger: 'blur' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    let param = toRaw(state.ruleForm);
                    state.repeatDis = true;
                    try{
                        let res:any;
                        if(props.repairInfo === ''){
                            res = await SMSDRFileAdd(param);
                        }else{
                            res = await SMSDRFileUpdate(param);
                        }
                        if(res.success){
                            if(res.success) uploadFile();
                        }else{
                            state.repeatDis = false;
                        }
                    }catch(error){ state.repeatDis = false; }
                }else{
                    state.repeatDis = false;
					return false;
                }
            })
        }

        /*** 上传图片 */
        const uploadFile = async() => {
            let rcs: any;
            if(fileRef.value && fileRef.value.fileList.length !== 0){
                let setArr:any = [];
                fileRef.value.fileList.map((i: any) => {setArr.push(i.raw)});
                let param: any = {};
                param.files = setArr;
                param.sourceId = sourceId;
                param.sourceType = 10;
                rcs = await sysFileInfoMultipleUpload(param);
                try{
                    if(rcs.success){
                        ctx.emit('controlUseClick');
                        ctx.emit('updateData');
                        state.repeatDis = false;
                    }else{
                        state.repeatDis = false;
                        ctx.emit('controlUseClick');
                    }
                }catch(error){ state.repeatDis = false; }
            }else{
                ctx.emit('controlUseClick');
                ctx.emit('updateData');
                state.repeatDis = false;
            }
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** getDictFun 获取课程类型字典值 */
        const getDictFun = async() => {
            let res: any;
            res = await sysFileInfoYitId({});
            if(res.success){
                sourceId = res.data;
                fileInfo.value = JSON.stringify({sourceId: res.data});
                state.ruleForm.l_FileId = res.data;
            }
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                // 状态数据重置
                state.repeatDis = false;
                if(props.repairInfo !== ''){
                    titleCon.value = '编辑'
                    let getData = JSON.parse(props.repairInfo);
                    getData.n_Year = String(getData.n_Year);
                    state.ruleForm = getData;
                    sourceId = 0;
                    fileInfo.value = JSON.stringify({sourceId: JSON.parse(props.repairInfo).l_FileId});
                    sourceId = JSON.parse(props.repairInfo).l_FileId;
                }else{
                    getDictFun();
                    titleCon.value = '新增';
                    state.ruleForm = {
                        n_Year: '', // 所属年份
                        v_Describe: '', // 描述
                        n_Type: 0, // 应急演练文件类型
                        l_FileId: '', // 应急文件id
                    }
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            typeOption: [
                {value: 0, label: '应急资源调查'},
                {value: 1, label: '应急风险评估'},
                {value: 2, label: '事故应急调查'},
            ],
            fileInfo,
            isAlter: 1,
            fileRef,
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.el-cascader){
        width: 100%;
    }
    :deep(.el-select){
        width: 100%!important;
    }
    :deep(.el-input){
        width: 100%;
    }
</style>